﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Module.MultiSiteFields.Interfaces;
using umbraco.interfaces;
using umbraco.cms.presentation.Trees;
using umbraco;
using System.Web.UI.WebControls;
using Module.MultiSiteFields.Controllers;

namespace Module.MultiSiteFields.Controls.DynamicTreePicker
{
    public class PrevalueEditor : UserControl, IMultiSiteDynamicTreePreValueEditor
    {
        public System.Web.UI.HtmlControls.HtmlInputCheckBox chkShowLabel;
        public System.Web.UI.HtmlControls.HtmlInputText txtMaxAmountItems;
        public IDataType DataType { get; set; }
        private DynamicTreePreValue _Data;
        public DynamicTreePreValue Data
        {
            get
            {
                if (Page.IsPostBack)
                {
                    _Data = new DynamicTreePreValue();
                    List<TreeStartPoint> items = new List<TreeStartPoint>();
                    string checkedTree = (Request["checktree"] ?? "").Trim();
                    foreach (string item in checkedTree.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        string selstartpoint = (Request["sel_" + item] ?? "").Trim();
                        if (!string.IsNullOrEmpty(selstartpoint))
                            items.Add(new TreeStartPoint() { TreeAlias = item, Alias = selstartpoint, Settings = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("StartFrom", selstartpoint) } });                        
                    }
                    _Data.Types = items.ToArray();
                    _Data.HideLabel = chkShowLabel != null && !chkShowLabel.Checked;
                    //max amount
                    int result=0;
                    if (int.TryParse(txtMaxAmountItems == null ? "" : txtMaxAmountItems.Value, out result) && result > 0) 
                        _Data.MaxAmountItems = result;
                    else 
                        _Data.MaxAmountItems = -1;
                }
                return _Data;
            }
            set { _Data = value; }
        }



        public virtual void Repeater_Init_TreeCollection(object sender , EventArgs e)
        {
            Repeater r=sender as Repeater;
            if (r==null) return ;
            BindAvailableStartPoints(r);
        }

        public DynamicTreePreValue _BData;
        private void BindAvailableStartPoints(Repeater r)
        {
            IStartPointsController startPoints=ObjectManager.Resolve<IStartPointsController>();
            IEnumerable<KeyValuePair<TreeDefinition,List<TreeStartPoint>>> datasource=
                startPoints
                .GetAll()
                .Where(ti => ti.Value.Count > 0)
                .OrderBy(ti => ti.Key.Tree.Alias);
            
            r.DataSource = datasource;
            _BData = Data;//store current data into the temp value;
            r.DataBind();
            if (txtMaxAmountItems != null) txtMaxAmountItems.Value = _BData.MaxAmountItems.ToString();
            if (chkShowLabel != null) chkShowLabel.Checked = !_BData.HideLabel;
        }

        public virtual IEnumerable<TreeStartPoint> SortBy(List<TreeStartPoint> dataToSort)
        {
            if (dataToSort == null) return null;
            TreeStartPointsComparer comparer=new TreeStartPointsComparer();
            return dataToSort.OrderBy(tp => tp.Alias).Distinct(comparer); 
        }
        public bool IsSelected(TreeDefinition treeItem)
        {
            if (_BData == null || _BData.Types==null) return false;
            int cnt=_BData.Types.Where(ti => ti.TreeAlias.Equals(treeItem.Tree.Alias, StringComparison.InvariantCultureIgnoreCase)).Count();
            return cnt > 0; 
        }

        public bool IsSelected(TreeStartPoint treeSPoint)
        {
            if (_BData == null || _BData.Types == null) return false;
            int cnt = _BData.Types.Where(ti =>ti.TreeAlias.Equals(treeSPoint.TreeAlias, StringComparison.InvariantCultureIgnoreCase) && ti.Alias.Equals(treeSPoint.Alias, StringComparison.InvariantCultureIgnoreCase) ).Count();
            return cnt > 0; 
        }

        private class TreeStartPointsComparer : System.Collections.Generic.IEqualityComparer<TreeStartPoint>
        {

            public bool Equals(TreeStartPoint x, TreeStartPoint y)
            {
                if (x == null || y == null) return false;
                return (x.Alias.Equals(y.Alias) && x.TreeAlias.Equals(y.TreeAlias));
            }

            public int GetHashCode(TreeStartPoint obj)
            {
                return obj.Alias.GetHashCode()+obj.TreeAlias.GetHashCode();
            }
        }
    }


}
